#!/bin/bash

# 检查指定域名的证书是否过期
check_certificate_expiry() {
    local domain="$1"
    local expiry_date
    # 使用 openssl 命令获取证书的过期日期
    expiry_date=$(echo | openssl s_client -servername "$domain" -connect "$domain:443" 2>/dev/null | openssl x509 -noout -enddate | cut -d= -f2)
    # 检查是否获取到过期日期
    if [[ -z "$expiry_date" ]]; then
        echo "Error: Unable to retrieve certificate for $domain"
        return 1
    fi

    local expiry_ts=$(date -d "$expiry_date" +%s)
    local current_ts=$(date +%s)
    local remaining_days=$(( (expiry_ts - current_ts) / 86400 ))

     echo "Certificate for $domain expires on: $expiry_date，expires in $remaining_days days"
    # 统一过期判断
    if (( remaining_days < 3 )); then
        echo "Warning: Certificate will expire in $remaining_days days"
        # 调用脚本申请证书并下载到 /data/etc/nginx/conf.d/ssl/
        sed -i "s/domain: \".*\"/domain: \"$domain\"/" /usr/local/scripts/cert_check/config.yaml
        /usr/local/scripts/cert_check/auto-down-cert
        # 检查证书是否下载成功, 如果成功则重启 nginx
        if [ $? -eq 0 ]; then
            echo "Certificate for $domain has been renewed."
            unzip -o /data/etc/nginx/conf.d/ssl/${domain}_nginx.zip -d /data/etc/nginx/conf.d/ssl/
            # 热载入 nginx
            docker exec mystifying_elgamal nginx -s reload
            return 0
        else
            echo "Error: Failed to renew certificate for $domain"
            return 1
        fi

        return 1
    fi

    echo "Certificate for $domain is valid."
    return 0
}

# ... 保持函数定义不变 ...

# 遍历所有传入的域名参数
for domain in "$@"; do
    echo "Checking certificate for: $domain"
    check_certificate_expiry "$domain"
    echo "----------------------------------"
done